package service

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	clients = map[string]*Node{}
)

type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

func Chat(c *gin.Context) {
	userId := c.Query("userId")
	FriendId := c.Query("friendId")

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	if _, ok := clients[userId]; !ok {
		clients[userId] = &Node{
			Conn: conn,
			Data: make(chan []byte),
		}
	}

	go ReceiveMsg(clients[userId], FriendId)
	go SendMsg(clients[userId])

}
func ReceiveMsg(myNode *Node, friendId string) {
	for {
		_, data, err := myNode.Conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}
		friendIdNode := clients[friendId]
		friendIdNode.Data <- data
	}
}

func SendMsg(myNode *Node) {
	for {
		select {
		case data := <-myNode.Data:
			if err := myNode.Conn.WriteMessage(websocket.TextMessage, data); err != nil {
				log.Println(err)
				return
			}
		}
	}
}
